import { createApp } from 'vue'

import VueMarkdownEditor from '@kangc/v-md-editor';
import createKatexPlugin from '@kangc/v-md-editor/lib/plugins/katex/cdn';
import '@kangc/v-md-editor/lib/style/base-editor.css';
import vuepressTheme from '@kangc/v-md-editor/lib/theme/vuepress.js';
import '@kangc/v-md-editor/lib/theme/style/vuepress.css';

import VMdPreviewHtml from '@kangc/v-md-editor/lib/preview-html';
import '@kangc/v-md-editor/lib/style/preview-html.css';


import { createPinia } from 'pinia'
import ViewUIPlus from 'view-ui-plus'
import 'view-ui-plus/dist/styles/viewuiplus.css'
import "@icon-park/vue-next/styles/index.css";
import "./assets/css/tailwind.css";
import App from './App.vue'
import router from './router'
//引入axios
import axios from 'axios'
import VueAxios from 'vue-axios'

import Prism from 'prismjs';

// 设置axios的默认基础URL
axios.defaults.baseURL = 'http://localhost:8080/api'
axios.defaults.withCredentials = true


VueMarkdownEditor.use(vuepressTheme, {
  Prism,
});
VueMarkdownEditor.use(createKatexPlugin());

const app = createApp(App)
app.config.globalProperties.$axios = axios
// 创建一个简单的事件总线对象
const eventBus = {
    listeners: {},
    
    // 监听事件
    on(event, callback) {
      if (!this.listeners[event]) {
        this.listeners[event] = [];
      }
      this.listeners[event].push(callback);
    },
    
    // 触发事件
    emit(event, data) {
      if (this.listeners[event]) {
        this.listeners[event].forEach(callback => {
          callback(data);
        });
      }
    },
    
    // 移除事件的监听器
    off(event, callback) {
      if (this.listeners[event]) {
        const index = this.listeners[event].indexOf(callback);
        if (index !== -1) {
          this.listeners[event].splice(index, 1);
        }
      }
    }
  };
app.provide('eventBus', eventBus);
app.use(VMdPreviewHtml)
app.use(VueMarkdownEditor)
app.use(createPinia())
app.use(router)
app.use(ViewUIPlus)
app.use(VueAxios,axios)
app.mount('#app')



router.beforeEach((to, from, next) => {
  //store的getters中定义获取用户信息的函数  getUser
  //userId为空说明用户未登录
  if(to.name==='register'){
    next()
  }else{
    let isLogin = localStorage.getItem('name');
    if (!isLogin) {//未登录
        if (to.path !== '/login') {//跳转到登录页
            return next({path: '/login'});
        }else {
            next();
        }
    }else {//已登录
        if (to.path === '/login') {//跳转到首页
            return next({path: '/'});
        }
        next();
    }
  }

});

